package ynu.edu.elmspringboot.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import ynu.edu.elmspringboot.mapper.CartMapper;
import ynu.edu.elmspringboot.mapper.OrderDetailetMapper;
import ynu.edu.elmspringboot.mapper.FoodMapper;
import ynu.edu.elmspringboot.po.Cart;
import ynu.edu.elmspringboot.po.OrderDetailet;
import ynu.edu.elmspringboot.po.Food;
import ynu.edu.elmspringboot.service.OrderDetailetService;

import java.util.List;

@Service
public class OrderDetailetServiceImpl extends ServiceImpl<OrderDetailetMapper, OrderDetailet> implements OrderDetailetService {

    @Autowired
    private OrderDetailetMapper orderDetailetMapper;

    @Autowired
    private FoodMapper foodMapper;

    @Autowired
    private CartMapper cartMapper;

    @Override
    public OrderDetailet getOrderDetailetWithFood(Integer orderId) {
        OrderDetailet orderDetailet = orderDetailetMapper.selectById(orderId);
        if (orderDetailet != null) {
            Food food = foodMapper.selectById(orderDetailet.getFoodId());
            orderDetailet.setFood(food);
        }
        return orderDetailet;
    }

    @Override
    public Boolean saveByCart(Integer orderId  ,String userId) {
        if (orderId == null) {
            return false;
        }
        //查询购物车
        List<Cart> userCart = cartMapper.selectList(new QueryWrapper<Cart>().eq("user_id", userId));

        userCart.forEach(cart -> {
            //添加订单详情
            OrderDetailet orderDetailet = new OrderDetailet();
            orderDetailet.setFoodId(cart.getFoodId());
            orderDetailet.setQuantity(cart.getQuantity());
            orderDetailet.setOrderId(orderId);
            orderDetailetMapper.insert(orderDetailet);

            //将购物车绑定到订单
            cart.setOrderId(orderId);
            cartMapper.updateById(cart);
        });
        return true;
    }

}